//
//  LivestockPropertyViewController.m
//  Trackit
//
//  Created by yaodaobin on 2017/4/17.
//  Copyright © 2017年 yaodaobin. All rights reserved.
//

#import "LivestockPropertyViewController.h"
#import "LivestockPropertyHeaderView.h"
#import "PropertyCollectionCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZImageManager.h"
#import "TZVideoPlayerController.h"
#import "TZPhotoPreviewController.h"
#import "TZGifPhotoPreviewController.h"
#import "TZImagePickerController.h"

#define PhotoColumnNumber 4
#define PhotoMaxNumber 9

@interface LivestockPropertyViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate>

@property (nonatomic, strong) LivestockPropertyHeaderView *headerView;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) NSMutableArray *selectedPhotos;
@property (nonatomic, strong) NSMutableArray *selectedAssets;
@property (nonatomic, strong) NSMutableDictionary *infoDictionary;
@property (nonatomic, strong) NSMutableArray *uploadImageInfos;
@property (nonatomic, assign) CGFloat offsetY;
@end

@implementation LivestockPropertyViewController
#pragma mark - Controller LifeCycle
- (void)back {
    [self.taskDetail.locationInfo clearData];
    [super back];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initParams];
    [self initUI];
    [self reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(handleWillShowKeyboard:)
//                                                 name:UIKeyboardWillShowNotification
//                                               object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(handleWillHideKeyboard:)
//                                                 name:UIKeyboardWillHideNotification
//                                               object:nil];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)initParams {
    [super initParams];
    self.selectedPhotos = [NSMutableArray array];
    self.selectedAssets = [NSMutableArray array];
    self.infoDictionary = [NSMutableDictionary dictionary];
    self.uploadImageInfos = [NSMutableArray array];
    
}

- (void)initUI {
    [super initUI];
    [self setCustomTitle:NSLocalizedString(@"属性信息", nil)];
    UIBarButtonItem *rightBtn = [UIBarButtonItem barItemWithTitle:NSLocalizedString(@"确定", nil) target:self action:@selector(submit)];
    self.navigationItem.rightBarButtonItem = rightBtn;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat margin = 20;
    CGFloat row = 10;
    CGFloat itemWH = (kScreenWidth - (PhotoColumnNumber - 1) * row - 40) / PhotoColumnNumber;
    layout.itemSize = CGSizeMake(floorf(itemWH), floorf(itemWH));
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, margin, 0);
    [self.collectionView registerClass:[PropertyCollectionCell class] forCellWithReuseIdentifier:@"PropertyCollectionCell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ReusableHeaderView"];
    
}

#pragma mark - Getter
- (LivestockPropertyHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[LivestockPropertyHeaderView alloc] init];
        _headerView.taskDetail = self.taskDetail;
        _headerView.homeVC = self;
    }
    return _headerView;
}

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (iOS9Later) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}

#pragma mark - Action
- (void)submit {
    
    if (![self.headerView validateFillAll]) {
        return;
    }
    
    NSString *guid = [CommonFunction stringWithUUID];

    NSMutableDictionary *dic = [self.headerView getInfo];
    [dic safeSetObject:guid forKey:@"ObjId"];
    NSMutableArray *array = [NSMutableArray array];
    for (UploadImageInfo *info in self.uploadImageInfos) {
        NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
        [tempDic safeSetObject:info.taskDetailID forKey:@"taskDetailID"];
        [tempDic safeSetObject:guid forKey:@"objId"];
        [tempDic safeSetObject:info.photoSeq forKey:@"photoSeq"];
        [tempDic safeSetObject:info.photoDate forKey:@"photoDate"];
        [tempDic safeSetObject:info.username forKey:@"username"];
        [tempDic safeSetObject:info.password forKey:@"password"];
        [tempDic safeSetObject:info.localPath forKey:@"localPath"];
        [array addObject:tempDic];
    }
    
    if (self.propertyBlock) {
        self.propertyBlock(dic,array,[NSArray arrayWithArray:_uploadImageInfos]);
    }
    [self.taskDetail.locationInfo clearData];
    [super back];
}

- (void)deleteBtnClik:(UIButton *)sender {
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    [_selectedAssets removeObjectAtIndex:sender.tag];
    
    [self.collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [self.collectionView reloadData];
    }];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.headerView resignFirstResponder];
}

#pragma mark - UICollectionViewLayout
- (UIEdgeInsets) collectionView:(UICollectionView *)collectionView
                         layout:(UICollectionViewLayout *)collectionViewLayout
         insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 10, 0, 10);
}

#pragma mark - UICollectionView
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    NSArray *array = [TaskListModel getPropertyValueArray:self.taskDetail.collectDataType];
    CGFloat height = 0;
    for (NSArray *ar in array) {
        height += ar.count * 44 + 10;
    }
    return CGSizeMake(collectionView.width, height);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    //从缓存中获取 Headercell
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:
                                                UICollectionElementKindSectionHeader withReuseIdentifier:@"ReusableHeaderView" forIndexPath:indexPath];
        [headerView addSubview:self.headerView];
        [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsZero);
        }];
        return headerView;
    }
    return nil;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _selectedPhotos.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PropertyCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PropertyCollectionCell" forIndexPath:indexPath];
    cell.videoImageView.hidden = YES;
    if (indexPath.row == _selectedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"add"];
        cell.deleteBtn.hidden = YES;
        cell.gifLable.hidden = YES;
    } else {
        cell.imageView.image = _selectedPhotos[indexPath.row];
        cell.asset = _selectedAssets[indexPath.row];
        cell.deleteBtn.hidden = NO;
    }
    cell.deleteBtn.tag = indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _selectedPhotos.count) {
        kWeakSelf
        [self jxt_showActionSheetWithTitle:nil message:nil appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
            alertMaker.
            addActionCancelTitle(NSLocalizedString(@"取消", nil)).
            addActionDefaultTitle(NSLocalizedString(@"拍照", nil)).
            addActionDefaultTitle(NSLocalizedString(@"相册", nil));
        } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
            if (buttonIndex == 1) {
                [weakSelf takePhoto];
            } else if (buttonIndex == 2) {
                [weakSelf pushImagePickerController];
            }
        }];
    } else { // preview photos or video / 预览照片或者视频
        id asset = _selectedAssets[indexPath.row];
        BOOL isVideo = NO;
        if ([asset isKindOfClass:[PHAsset class]]) {
            PHAsset *phAsset = asset;
            isVideo = phAsset.mediaType == PHAssetMediaTypeVideo;
        } else if ([asset isKindOfClass:[ALAsset class]]) {
            ALAsset *alAsset = asset;
            isVideo = [[alAsset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo];
        }
        if ([[asset valueForKey:@"filename"] containsString:@"GIF"]) {
            TZGifPhotoPreviewController *vc = [[TZGifPhotoPreviewController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypePhotoGif timeLength:@""];
            vc.model = model;
            [self presentViewController:vc animated:YES completion:nil];
        } else if (isVideo) { // perview video / 预览视频
            TZVideoPlayerController *vc = [[TZVideoPlayerController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypeVideo timeLength:@""];
            vc.model = model;
            [self presentViewController:vc animated:YES completion:nil];
        } else { // preview photos / 预览照片
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:indexPath.row];
            imagePickerVc.maxImagesCount = PhotoMaxNumber;
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                _selectedPhotos = [NSMutableArray arrayWithArray:photos];
                _selectedAssets = [NSMutableArray arrayWithArray:assets];
                [self.collectionView reloadData];
            }];
            [self presentViewController:imagePickerVc animated:YES completion:nil];
        }
    }
}


- (void)pushImagePickerController {
    kWeakSelf
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:PhotoMaxNumber columnNumber:PhotoColumnNumber delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.isSelectOriginalPhoto = YES;
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.sortAscendingByModificationDate = NO;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.needCircleCrop = NO;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos.count > 0) {
            [weakSelf.selectedPhotos addObjectsFromArray:photos];
            [weakSelf.selectedAssets addObjectsFromArray:assets];
            [weakSelf reloadData];
            
            [weakSelf parseSelectAssets:assets];
        }
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)parseSelectAssets:(NSArray *)asstes {
    NSDateFormatter *dateFormatterSeq = [[NSDateFormatter alloc] init];
    dateFormatterSeq.dateFormat = @"YYYYMMdd";

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"YYYYMMdd HH:mm:ss";
    NSString *string = [dateFormatter stringFromDate:[NSDate date]];
    int i = 0;
    for (PHAsset *asset in asstes) {
        UploadImageInfo *info = [[UploadImageInfo alloc] init];
        info.username = APP_DELEGATE.user.userName;
        info.password = APP_DELEGATE.user.password;
        info.taskDetailID = self.taskDetail.taskDetailID;
        NSArray *array = [asset.localIdentifier componentsSeparatedByString:@"/"];
        NSString *objString = @"";
        if (array.count > 0) {
            objString = array[0];
        }
        info.objId = objString;
        info.photoDate = [dateFormatterSeq stringFromDate:asset.creationDate];
        info.photoSeq = @"1";
        info.localPath = [NSString stringWithFormat:@"Photo[%@]ID[%@]_%d.jpg",string,self.taskDetail.taskDetailID,i];
        info.image = self.selectedPhotos[i];
        i++;
        [self.uploadImageInfos addObject:info];
    }
}

#pragma mark - UIImagePickerController

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
        // 拍照之前还需要检查相册权限
        
    } else if ([TZImageManager authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        alert.tag = 1;
        [alert show];
    } else if ([TZImageManager authorizationStatus] == 0) { // 正在弹框询问用户是否允许访问相册，监听权限状态
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            return [self takePhoto];
        });
    } else { // 调用相机
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = sourceType;
            self.imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            [self presentViewController:_imagePickerVc animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
    }
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image completion:^(NSError *error){
            if (error) {
                [tzImagePickerVc hideProgressHUD];
                NSLog(@"图片保存失败 %@",error);
            } else {
                [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES completion:^(TZAlbumModel *model) {
                    [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                        [tzImagePickerVc hideProgressHUD];
                        TZAssetModel *assetModel = [models firstObject];
                        if (tzImagePickerVc.sortAscendingByModificationDate) {
                            assetModel = [models lastObject];
                        }
                        [self refreshCollectionViewWithAddedAsset:assetModel.asset image:image];
                    }];
                }];
            }
        }];
    }
}

- (void)refreshCollectionViewWithAddedAsset:(id)asset image:(UIImage *)image {
    [_selectedAssets addObject:asset];
    [_selectedPhotos addObject:image];
    [self.collectionView reloadData];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - Notifications
#pragma mark - Keyboard
- (void)handleWillShowKeyboard:(NSNotification *)notification {
    CGPoint offset = self.collectionView.contentOffset;
    self.offsetY = offset.y;
    offset.y = [self.headerView currentOffset];
    self.collectionView.contentOffset = offset;
}

- (void)handleWillHideKeyboard:(NSNotification *)notification {
    [self.headerView resignFirstResponder];
    self.collectionView.contentOffset = CGPointMake(0, self.offsetY);
}

#pragma mark - ScrollView
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.headerView resignFirstResponder];
    self.collectionView.contentOffset = CGPointMake(0, self.offsetY);
}
@end
